import { Router } from 'express'
import { body } from 'express-validator'
import { asyncHandler } from '../middleware/errorHandler'
import { handleValidationErrors, validatePagination } from '../middleware/validation'
import { authenticate, AuthRequest } from '../middleware/auth'
import { AIService } from '../services/aiService'

const router = Router()
const aiService = new AIService()

// All routes require authentication
router.use(authenticate)

// Chat with AI
router.post('/chat', [
  body('message').notEmpty().withMessage('Message is required'),
  body('sessionId').optional().isString().withMessage('Session ID must be a string'),
  body('scenario').optional().isString().withMessage('Scenario must be a string'),
  body('role').optional().isString().withMessage('Role must be a string'),
], handleValidationErrors, asyncHandler(async (req: AuthRequest, res) => {
  const { message, sessionId, scenario, role } = req.body
  
  const response = await aiService.chat({
    userId: req.user!.id,
    message,
    sessionId: sessionId || req.user!.id.toString(),
    scenario,
    role,
  })
  
  res.json({
    success: true,
    data: response,
  })
}))

// Generate content
router.post('/generate', [
  body('type').isIn(['activity', 'rule', 'meeting', 'venue']).withMessage('Invalid content type'),
  body('prompt').notEmpty().withMessage('Prompt is required'),
], handleValidationErrors, asyncHandler(async (req: AuthRequest, res) => {
  const { type, prompt, options = {} } = req.body
  
  const content = await aiService.generateContent({
    type,
    prompt,
    userId: req.user!.id,
    options,
  })
  
  res.json({
    success: true,
    data: content,
  })
}))

// Get chat history
router.get('/chat/history', validatePagination, asyncHandler(async (req: AuthRequest, res) => {
  const { page, limit, sessionId } = req.query as any
  
  const history = await aiService.getChatHistory({
    userId: req.user!.id,
    sessionId,
    page,
    limit,
  })
  
  res.json({
    success: true,
    data: history,
  })
}))

// Get available AI models
router.get('/models', asyncHandler(async (req: AuthRequest, res) => {
  const models = await aiService.getAvailableModels()
  
  res.json({
    success: true,
    data: models,
  })
}))

// Get AI scenarios
router.get('/scenarios', asyncHandler(async (req: AuthRequest, res) => {
  const scenarios = await aiService.getAvailableScenarios()
  
  res.json({
    success: true,
    data: scenarios,
  })
}))

// Get AI roles
router.get('/roles', asyncHandler(async (req: AuthRequest, res) => {
  const roles = await aiService.getAvailableRoles()
  
  res.json({
    success: true,
    data: roles,
  })
}))

// Clear chat history
router.delete('/chat/history', [
  body('sessionId').optional().isString().withMessage('Session ID must be a string'),
], handleValidationErrors, asyncHandler(async (req: AuthRequest, res) => {
  const { sessionId } = req.body
  
  await aiService.clearChatHistory({
    userId: req.user!.id,
    sessionId,
  })
  
  res.json({
    success: true,
    message: 'Chat history cleared successfully',
  })
}))

// Get AI usage statistics
router.get('/usage', asyncHandler(async (req: AuthRequest, res) => {
  const stats = await aiService.getUsageStatistics(req.user!.id)
  
  res.json({
    success: true,
    data: stats,
  })
}))

// Test AI connection
router.post('/test', asyncHandler(async (req: AuthRequest, res) => {
  const isConnected = await aiService.testConnection()
  
  res.json({
    success: true,
    data: {
      connected: isConnected,
      timestamp: new Date().toISOString(),
    },
  })
}))

export { router as aiRouter }